<?php
/**
 * IG_Web_Element_Table_Cell
 *
 * @author maomao.thx@gmail.com
 * @copyright Copyright (c) 2009 Green Shore (http://www.iwgame.com)
 * @version $Id: Cell.php 589 2011-06-01 00:59:38Z mmxie $
 */
require_once ('IG/Web/Element.php');
class IG_Web_Element_Table_Cell extends IG_Web_Element
{
    protected $_format = null;

    /**
     *
     * @param string $format
     * @return IG_Web_Element_Table_Cell
     */
    public function setFormat($format)
    {
        $this->_format = $format;
        return $this;
    }

    /**
     * @return string
     */
    public function getFormat()
    {
        return $this->_format;
    }

    /**
     *
     * @param string $content
     * @return string
     */
    function render($content)
    {
        $attribs = $this->getAttribs();
        if (isset($attribs['enable']) && $attribs['enable'] == false) {
            return $content;
        }

        if ($this->getName() != null) {
            $attribs['name'] = $this->getName();
        }

        if ($this->getId() != null) {
            $attribs['id'] = $this->getId();
        }

        if (isset($attribs['value'])) {
            $value = $this->_formatHtml($attribs['value']);
            unset($attribs['value']);

        } else {
            $value = '';
        }
        // build the element
        $xhtml = '<td'
                . $this->_htmlAttribs($attribs)
                . '>' . PHP_EOL
                . $value . PHP_EOL;

        return $content . $xhtml . '</td>';
    }

    /**
     *
     * @param mixed $value
     * @return string
     */
    protected function _formatHtml($value)
    {
        if ($this->getFormat() != null) {
            try {
                if (is_array($value)) {
                    $value = vsprintf($this->getFormat(), $value);
                } else {
                    $value = sprintf($this->getFormat(), $value);
                }
            } catch (Exception $e) {
                throw new IG_Web_Exception('Too few arguments when format html');
            }
        }
        return $value;
    }
}